package com.browsesoft.authentication;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.w3c.dom.Element;

import com.browsesoft.ExtendElement;
import com.browsesoft.PropertiesService;

/**
 * 认证模式工厂，单列缓存模式
 */
public class AuthenticationFactory {
	private Map authenticationModes = new HashMap();

	/**
	 * 默认认证模式，如果参数中没有指明需要的认真模式，采用默认认证模式
	 */
	private AuthenticationMode defaultMode;

	private static AuthenticationFactory instance = new AuthenticationFactory();

	private AuthenticationFactory() {
	}

	public static AuthenticationFactory getInstance() {
		return instance;
	}

	public synchronized AuthenticationMode getMode(String name) {
		AuthenticationMode mode = (AuthenticationMode) this.authenticationModes
				.get(name);
		if (mode == null) {
			mode = this.createMode(name);
			this.authenticationModes.put(name, mode);
		}
		return mode;
	}

	private AuthenticationMode createMode(String name) {
		try {
			// 从属性文件里得到模式对应的元素
			Element root = PropertiesService.getDocument().getDocumentElement();
			List list = ExtendElement.findElementsByTagName(root,
					"AuthenticationMode", "name", name);
			Element me = (Element) list.get(0);
			// 根据元素里的类名生成认证对象
			String cname = me.getAttribute("class");
			AuthenticationMode result = (AuthenticationMode) Class.forName(
					cname).newInstance();
			// 设置配置元素
			result.setElement(me);
			// 如果是默认认证模式，设置全局默认认证模式
			if (result.isDefaultMode()) {
				this.defaultMode = result;
			}
			return result;
		} catch (Exception ex) {
			throw new RuntimeException("认证方式错误：" + name, ex);
		}
	}

	/**
	 * 得到默认认证模式
	 */
	public AuthenticationMode getDefaultMode() {
		return this.defaultMode;
	}
}
